package com.siteseat.common.collection;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ChainedIterator<E> implements Iterator<E> {

  private Iterator<E> current;

  private Iterable<E> others;

  /**
   * @param nextIterator
   */
  public ChainedIterator( Iterator<E> me, Iterable<E> others ) {
    this.others = others;
    this.current = me;
  }

  /**
   * @return
   */
  public Iterable<E> others() {
    return this.others;
  }

  /**
   * 
   */
  @SuppressWarnings( "unchecked" )
  protected void tryToForward() {
    Iterator<E> newItr = others.iterator();
    this.current = newItr;
    if( newItr instanceof ChainedIterator ) {
      this.others = ( (ChainedIterator<E>)newItr ).others();
    } else {
      this.others = null;
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean hasNext() {
    if( this.current.hasNext() ) {
      return true;
    }

    if( this.others == null ) {
      return false;
    }

    tryToForward();

    return hasNext();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public E next() {
    if( this.current.hasNext() ) {
      return this.current.next();
    }

    if( this.others == null ) {
      throw new NoSuchElementException();
    }

    tryToForward();

    return next();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void remove() {
    this.current.remove();
  }

}
